package com.lt.common;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.NumberFormat;

public class FormatHelper {

    private static FormatHelper instance;
    //使用0.00不足位补0，#.##仅保留有效位
    public static final String patternCny = "#,###,##0.00";
    public static final String patternCnyB = "#,###,###.##";
    private static final RoundingMode mode = RoundingMode.DOWN;

    private FormatHelper() {
    }

    public static FormatHelper getInstance() {
        if (instance == null) {
            synchronized (FormatHelper.class) {
                instance = new FormatHelper();
            }
        }
        return instance;
    }


    public String format(String pattern, double d) {
        DecimalFormat decimalFormat = new DecimalFormat(pattern);
        decimalFormat.setRoundingMode(mode);
        return decimalFormat.format(d);
    }

    public String format(String pattern, BigDecimal bd) {
        DecimalFormat decimalFormat = new DecimalFormat(pattern);
        decimalFormat.setRoundingMode(mode);
        return decimalFormat.format(bd);
    }

    public String formatCny(double d) {
        return format(patternCny, d);
    }

    /**
     * Double 转string 去除科学记数法显示
     *
     * @param groupingUsed groupingUsed
     */
    public String double2Str(Double d, boolean groupingUsed) {
        if (d < 0.00000001) {
            return "0";
        }
        NumberFormat nf = NumberFormat.getNumberInstance();
        nf.setMaximumFractionDigits(8);
        nf.setRoundingMode(mode);
        nf.setGroupingUsed(groupingUsed);
        return (nf.format(d));
    }

    /**
     * @param digit 需要保留的小数位数
     */
    public String double2Str(Double d, int digit) {
        NumberFormat nf = NumberFormat.getNumberInstance();
        nf.setMaximumFractionDigits(digit);
        nf.setRoundingMode(RoundingMode.HALF_UP);
        nf.setGroupingUsed(false);
        return nf.format(d);
    }
}
